package com.qipay.admin.ips.controller;

import com.qipay.admin.BaseController;
import com.qipay.admin.msg.vo.MessageJSONDTO;
import com.qipay.baas.model.WhiteIps;
import com.qipay.ips.service.IpsService;
import com.qipay.security.UserDetailsServiceImpl;
import com.qipay.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;

@Controller
@RequestMapping("/ips")
public class IpsController extends BaseController {
    @Autowired
    IpsService ipsService;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Result<List<MessageJSONDTO>> add(
            @AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
            @RequestParam(value = "ipAddress", required = true) String ipAddress,
            HttpServletResponse resp) throws IOException, ParseException {
        ipsService.add(loginUser,ipAddress);
        Result<List<MessageJSONDTO>> result = new Result<>();
        result.setCode(200);
        result.setData(null);
        return result;
    }

    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public ModelAndView query(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                              HttpServletResponse resp) throws IOException, ParseException {

        List<WhiteIps> whiteIpsList = ipsService.query(loginUser);
        ModelAndView modelAndView = createModelAndView("ips");
        modelAndView.addObject("ips", whiteIpsList);
        return modelAndView;
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Result<List<MessageJSONDTO>> delete(@AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser,
                                               @RequestParam(value = "id", required = true) long id,
                                               HttpServletResponse resp) throws IOException, ParseException {
        ipsService.delete(loginUser, id);
        Result<List<MessageJSONDTO>> result = new Result<>();
        result.setCode(200);
        result.setData(null);
        return result;
    }
}
